package me.tianle.login.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {


    @RequestMapping("")
    public ModelAndView index() {
        return new ModelAndView("index");
    }

    @RequestMapping("/add")
    public String add(){
        return "/per/addUser";
    }

    @RequestMapping("/detail")
    public String detail(){
        return "/per/detail";
    }

    @RequestMapping("/del")
    public String del(){
        return "/per/delUser";
    }

    @RequestMapping("/update")
    public String update(){
        return "/per/updateUser";
    }

    //未授权页面跳转
    @RequestMapping("/noAuth")
    public String noAuth(){
        return "noAuth";
    }

    //登陆成功页面
    @RequestMapping("/success")
    public String success(){
        return "success";
    }

    //退出当前用户
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }

    /**
     * 登录逻辑处理
     */
    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        System.out.println("name="+username);
        /**
         * 使用Shiro编写认证操作
         */
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //3.执行登录方法
        try {
            subject.login(token);

            //登录成功
            //跳转到test.html
            return "redirect:/success";
        } catch (UnknownAccountException e) {
            //e.printStackTrace();
            //登录失败:用户名不存在
            model.addAttribute("msg", "用户名不存在！");
            return "index";
        }catch (IncorrectCredentialsException e) {
            //e.printStackTrace();
            //登录失败:密码错误
            model.addAttribute("msg", "密码错误！");
            return "index";
        }
    }

}
